<template>
  <div :class="isBack ? 'waybill-box box-height' : 'waybill-box'">
    <div :class="isBack ? 'waybill-content' : 'waybill-content content-width'">
      <WaybillTitleBar title="运单详情"
                       :value="waybill"
                       :is-all="all"
                       :is-back="isBack"
                       :one-bill-flag="oneBillFlag"
                       :close-flag="closeFlag"
                       :is-close="isClose"
                       :show-carrier="showCarrier"
                       @sign="handleSign"
                       @receipt="receiptDialogVisible = true"
                       @reject="handleReject"
                       @recallDispatch="recallDialogVisible = true"
                       @agree="handleAgreeClose"
                       @accept="handleAccept"
                       @cancelSplit="handleCancelSplit" />
      <div style="padding: 20px 20px 10px">
        <WaybillDescriptions :value="waybill" />
      </div>
      <el-row v-if="showCarrier"
              style="padding: 0 20px">
        <WaybillCarrier :value="waybill" />
      </el-row>
      <div style="padding: 0 20px"><el-divider /></div>
      <el-row :gutter="40">
        <el-col :span="12">
          <WaybillCustomer :value="waybill" />
        </el-col>
        <el-col :span="12">
          <WaybillConsignee :value="waybill" />
        </el-col>
      </el-row>
      <SimpleTab>
        <WaybillGoodsList :value="waybill"
                          :is-all="all"
                          :one-bill-flag="oneBillFlag"
                          :is-close="isClose"
                          @input="handleGoodsListInput" />
      </SimpleTab>
      <SimpleTab v-if="showReceiptPics"
                 title="其他信息">
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">签收时间: </el-col>
          <el-col :span="20"
                  class="value-sty">
            {{signTime}}
          </el-col>
        </el-row>
        <el-row v-if="waybill.isRootWaybill && waybill.waybillType === 10"
                class="info_sty">
          <el-col :span="2"
                  class="label-sty">延期原因: </el-col>
          <el-col :span="20"
                  class="value-sty">
            {{(waybill.sign && waybill.sign.delayReasonDesc) || '--'}}
          </el-col>
        </el-row>
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">签收照片: </el-col>
          <el-col :span="20">
            <Thumbnails v-if="signPics.length"
                        :images="signPics"
                        :checkable="false" />
            <span v-else>--</span>
          </el-col>
        </el-row>
        <el-row v-if="waybill.isRootWaybill && waybill.waybillType === 10"
                class="info_sty">
          <el-col :span="2"
                  class="label-sty">拒签照片: </el-col>
          <el-col :span="20">
            <Thumbnails v-if="rejectSignPics.length"
                        :images="rejectSignPics"
                        :checkable="false" />
            <span v-else>--</span>
          </el-col>
        </el-row>
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">回单照片: </el-col>
          <el-col :span="20">
            <WaybillReceiptPics :value="waybill"
                                :is-all="all"
                                :one-bill-flag="oneBillFlag"
                                @files="handleReceiptPicsInput" />
          </el-col>
        </el-row>
      </SimpleTab>
      <SimpleTab title="运输信息">
        <WaybillArguments :value="waybill" />
        <WaybillAttachments :value="waybill" />
      </SimpleTab>
      <WaybillReceiptSubmit :value="waybill"
                            :visible.sync="receiptDialogVisible"
                            :before-submit="handleReceiptSubmitBefore"
                            :upload-receipt-pics="receiptPics"
                            :loading.sync="loading"
                            @submit="handleReceiptSubmit" />
      <WaybillSignSubmit :value="waybill"
                         :visible.sync="signDialogVisible"
                         :before-submit="handleSignSubmitBefore"
                         :loading.sync="loading"
                         @submit="handleSignSubmit" />
      <WaybillRejectSubmit :value="waybill"
                           :visible.sync="rejectDialogVisible"
                           :before-submit="handleRejectSubmitBefore"
                           :loading.sync="loading"
                           @submit="handleRejectSubmit" />
      <WaybillRecallSubmit :value="waybill"
                           :visible.sync="recallDialogVisible"
                           :before-submit="handleRecallSubmitBefore"
                           :loading.sync="loading"
                           @submit="handleRecallSubmit" />
      <SimpleTab v-if="showScore && waybill.score"
                 title="签收评价">
        <WaybillSignScore :value="waybill.score.star"
                          :score-label-desc="scoreLabelDesc"
                          :score-desc="waybill.score.remarks" />
      </SimpleTab>
      <SimpleTab v-show="isTrack"
                 title="跟踪信息">
        <Information :value="track" />
      </SimpleTab>
    </div>
  </div>
</template>
<script>
import { transport, track } from "@/api/index";
import Thumbnails from "@basic/Thumbnails.vue";
import SimpleTab from "@/components/basic/SimpleTab.vue";
import WaybillCustomer from "@/components//waybill/WaybillCustomer";
import WaybillCarrier from "@/components//waybill/WaybillCarrier";
import WaybillAttachments from "@/components/waybill/WaybillAttachments";
import WaybillDescriptions from "@/components//waybill/WaybillDescriptions";
import WaybillConsignee from "@/components/waybill/WaybillConsignee";
import WaybillArguments from "@/components/waybill/WaybillArguments";
import WaybillReceiptPics from "@/components/waybill/WaybillReceiptPics";
import WaybillReceiptSubmit from "@/components/waybill/WaybillReceiptSubmit";
import WaybillRejectSubmit from "@/components/waybill/WaybillRejectSubmit";
import WaybillSignSubmit from "@/components/waybill/WaybillSignSubmit";
import WaybillRecallSubmit from "@/components/waybill/WaybillRecallSubmit";
import WaybillTitleBar from "@/components/waybill/WaybillTitleBar";
import WaybillGoodsList from "@/components/waybill/WaybillGoodsList";
import Information from "@/components/track/Information.vue";
import WaybillSignScore from "@/components/waybill/WaybillSignScore.vue";
import { returnCompareTime } from "@/libs/util.js";

import {
  ABOUT_CODES,
  STATUS_CODES,
  ATTACHMENT_TYPES
} from "@/components/waybill/waybill.mixin.js";
export default {
  name: "WaybillDetail",
  components: {
    SimpleTab,
    Thumbnails,
    WaybillTitleBar,
    WaybillCustomer,
    WaybillConsignee,
    WaybillCarrier,
    WaybillDescriptions,
    WaybillArguments,
    WaybillReceiptPics,
    WaybillAttachments,
    WaybillReceiptSubmit,
    WaybillSignSubmit,
    WaybillRecallSubmit,
    WaybillGoodsList,
    WaybillRejectSubmit,
    WaybillSignScore,
    Information
  },
  data () {
    return {
      waybill: {},
      loading: false,
      signDialogVisible: false,
      receiptDialogVisible: false,
      rejectDialogVisible: false,
      recallDialogVisible: false,
      receiptPics: [], //回单照片
      goodsList: [],
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      rejectType: null, //拒绝类型 1拒绝接收 2拒绝关单
      isBack: true
    };
  },
  computed: {
    waybillId () {
      return this.waybill?.id || this.waybill?.waybillId;
    },
    showScore () {
      return [40, 50].includes(this.waybill.status) && this.waybill.score;
    },
    showCarrier () {
      // 是否是承运方运单
      const { name } = this.$route
      return ['carrierWayBillWindow', 'carrierWayBillDetail', 'carrierWayBillCloseDetail'].includes(name);
    },
    showReceiptSubmit () {
      return this.waybill.status === 40 && this.waybill.sign;
    },
    showReceiptPics () {
      return this.waybill.status === 40 || this.waybill.status === 50;
    },
    hasSignNumOver () {
      return this.goodsList.filter((goods) => goods.isSignNumOver).length > 0;
    },
    hasSignNumLack () {
      return this.goodsList.filter((goods) => goods.isSignNumLack).length > 0;
    },
    hasSignNumZero () {
      return this.goodsList.filter((goods) => goods.isSignNumZero).length > 0;
    },
    hasCombineId () {
      return this.waybill.combineId;
    },
    isCompleted () {
      return this.waybill.status === STATUS_CODES.RECEIPTED;
    },
    signTime () {
      return this.waybill?.sign?.signAtAmend;
    },
    signPics () {
      return (this.waybill?.attachments || [])
        .filter((pic) => pic.type === ATTACHMENT_TYPES.SIGN_PIC)
        .map((pic) => pic.url);
    },
    rejectSignPics () {
      return (this.waybill?.sign?.refusedAttachments || [])
        .filter((pic) => pic.type === ATTACHMENT_TYPES.REJECT_SIGN_PIC)
        .map((pic) => pic.url);
    },
    scoreLabelDesc () {
      let desc = this.waybill?.score?.labels?.toString()
      return desc ? desc.replace(',', '，') : null
    },
    all () {
      // 新窗口打开
      const { name } = this.$route
      return ['wayBillDetailWindow', 'carrierWayBillWindow'].includes(name);
    },
    oneBillFlag () {
      // 合单页进入
      return this.$route.query?.oneBillFlag;
    },
    isClose () {
      // 运单关单
      const { name } = this.$route
      return ['wayBillCloseDetail', 'carrierWayBillCloseDetail'].includes(name);
    },
    // 关单待办或已关单
    closeFlag () {
      return [10, 20, 50, 60].includes(this.waybill?.close?.status);
    },
  },
  mounted () {
    this.loadWaybill();
    this.trackInformation();
  },
  methods: {
    async loadWaybill () {
      const { id, waybillId } = this.$route.query;
      let { code, data = {} } = await transport.getDetail(waybillId || id);
      if (0 === code) {
        this.waybill = data;
        if (this.oneBillFlag || this.all || !([-1, 10, 20, 30, 40, 21].includes(data?.status) || data?.close?.status === 20)) {
          this.isBack = false
        }
      }
    },
    closeWindowWait () {
      this.$router.back();
      // window.close();
    },
    /**
     * 重定向到合单
     */
    redirectCombinedWaybill () {
      const { combineId, combineStatus } = this.waybill;
      this.$router.push({
        name: combineStatus === 10 ? 'oneBill' : 'oneBillDetails',
        query: {
          combineId
        }
      });
    },
    handleReject (rejectType) {
      this.rejectType = rejectType;
      this.rejectDialogVisible = true;
    },
    handleRejectSubmitBefore (reject) {
      return true;
    },
    async handleRejectSubmit (reject) {
      this.loading = true;
      const { id: waybillId } = this.waybill;
      const { code, message } = await transport[this.rejectType === 1 ? 'refuse' : 'rejectClose']({
        waybillId,
        id: waybillId,
        ...reject
      })
        .catch(() => {
          this.loading = false;
        });
      if (0 === code) {
        this.loading = false;
        this.$message({ type: "success", message });
        this.rejectDialogVisible = false;
        this.closeWindowWait()
      }
    },
    handleRecallSubmitBefore (recall) {
      return true;
    },
    // 撤销调度
    async handleRecallSubmit (recall) {
      this.loading = true;
      const { id: waybillId } = this.waybill;
      const { code, message } = await transport.recallDispath({
        waybillId,
        id: waybillId,
        ...recall
      })
        .catch(() => {
          this.loading = false;
        });
      if (0 === code) {
        this.loading = false;
        this.$message({ type: "success", message });
        this.recallDialogVisible = false;
        this.closeWindowWait()
      } else if (code === -10341) {
        this.loading = false;
        this.$confirm(message, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.redirectCombinedWaybill();
        });
      } else {
        this.$message({ type: "error", message });
      }
    },
    handleReceiptSubmitBefore ({ receiptTime }) {
      if (!receiptTime) {
        this.$message({ type: "error", message: "回单时间不能为空" });
        return false;
      }
      if (this.hasSignNumOver) {
        this.$message.warning("实签数量不能大于物品数量！");
        return false;
      }

      if (this.hasSignNumLack) {
        this.$message.warning("实签数量+异常数量不能小于物品数量！");
        return false;
      }

      if (this.hasSignNumZero) {
        this.$message.warning("实签数量不能为空！");
        return false;
      }
      return true;
    },
    async handleReceiptSubmit (receipt) {
      this.loading = true;
      const attachments = this.receiptPics;
      const { receiptTime: receiptAt, receiptSignTime: receiptSignAt, syncUpAttachments } = receipt;
      const { orderId, id: waybillId } = this.waybill;

      if (receiptSignAt) {
        if (receiptAt && returnCompareTime(
          new Date(this.$moment(receiptSignAt).format("YYYY-MM-DD HH:mm:ss")),
          new Date(this.$moment(receiptAt).format("YYYY-MM-DD HH:mm:ss"))
        )) {
          this.loading = false;
          return this.$message({ type: "error", message: "回单时间不能早于签收时间" });
        }
      } else {
        if (receiptAt && returnCompareTime(
          new Date(this.$moment(this.signTime).format("YYYY-MM-DD HH:mm:ss")),
          new Date(this.$moment(receiptAt).format("YYYY-MM-DD HH:mm:ss"))
        )) {
          this.loading = false;
          return this.$message({ type: "error", message: "回单时间不能早于签收时间" });
        }
      }

      // 接口中quantity表示签收数量
      const receiptGoodsList = _.cloneDeep(this.goodsList);
      receiptGoodsList.forEach((goods) => {
        goods.quantity = goods.signQuantity;
        delete goods.goodsSign;
      });

      const { code, message } = await transport.receipt({
        waybillId,
        id: waybillId,
        orderId,
        attachments,
        goodsQuantity: receiptGoodsList,
        syncUpAttachments,
        receiptAt,
        receiptSignAt,
        ...receipt
      })
        .catch(() => {
          this.loading = false;
        });
      if (0 === code) {
        this.loading = false;
        this.$message({ type: "success", message });
        this.receiptDialogVisible = false;
        this.closeWindowWait();
      }
    },
    handleSign () {
      if (this.closeFlag) {
        return this.$message.warning("运单有关单待办需要处理，暂不能操作");
      }
      this.signDialogVisible = true
    },
    handleSignSubmitBefore (sign) {
      if (this.hasSignNumOver) {
        this.$message.warning("实签数量不能大于物品数量！");
        return false;
      }

      if (this.hasSignNumLack) {
        this.$message.warning("实签数量+异常数量不能小于物品数量！");
        return false;
      }

      if (this.hasSignNumZero) {
        this.$message.warning("实签数量不能为空！");
        return false;
      }
      return true;
    },
    async signVaild (sign, signGoodsList) {
      const { waybillId } = this.waybill;
      const response = await transport.checkSign({ waybillId })
      if (0 === response.code && response.data) {
        this.loading = true;
        this.sign(sign, signGoodsList)
      } else {
        this.$confirm(`${response.message}`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          this.sign(sign, signGoodsList)
        });

      }
    },
    async handleSignSubmit (sign) {
      // 接口中quantity表示签收数量
      const signGoodsList = _.cloneDeep(this.goodsList);
      signGoodsList.forEach((goods) => {
        goods.quantity = goods.signQuantity;
      });

      if ([1, 3].includes(this.waybill?.device?.trackType)) {
        this.signVaild(sign, signGoodsList);
      } else {
        this.loading = true;
        this.sign(sign, signGoodsList)
      }
    },
    async sign (sign, signGoodsList) {
      const { orderId, id: waybillId } = this.waybill;
      const response = await transport.sign({
        waybillId,
        id: waybillId,
        orderId,
        goodsQuantity: signGoodsList,
        ...sign
      })
        .catch(() => {
          this.loading = false;
        });
      if (0 === response?.code) {
        this.loading = false;
        this.$message({ type: "success", message: response.message });
        this.signDialogVisible = false;
        this.closeWindowWait();
      }
    },
    handleGoodsListInput (goodsList) {
      this.goodsList = goodsList;
    },
    handleReceiptPicsInput (receiptPics) {
      this.receiptPics = receiptPics;
    },
    async handleAgreeClose () {
      const { id: waybillId } = this.waybill;
      let { message, code } = await transport.agree({ waybillId });
      if (code === 0) {
        this.$message({ type: "success", message });
        this.closeWindowWait()
      } else if (code == ABOUT_CODES.JUMP_COMBINED_WAYBILL) {
        this.$confirm(message, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.redirectCombinedWaybill();
        });
      } else if (code != ABOUT_CODES.JUMP_COMBINED_WAYBILL) {
        this.$message({
          type: "error",
          message
        });
      }
    },
    //接收
    async handleAccept () {
      let { message, code } = await transport.accept({
        waybillId: this.waybillId
      });
      if (code === 0) {
        this.$message({ type: "success", message });
        this.$router.back()
      }
    },
    // 撤销拆单
    async handleCancelSplit () {
      let { message, code } = await transport.cancelSplit({
        waybillId: this.waybillId
      });
      if (code === 0) {
        this.$message({ type: "success", message });
        this.closeWindowWait()
      }
    },
    // 跟踪信息
    async trackInformation () {
      const { id, waybillId } = this.$route.query;
      let type = 'waybill'
      let { code, data } = await track.information(waybillId || id, type);
      if (code === 0 && data.length) {
        data.map(item => {
          item.timestamp = item.message.slice(0, item.message.indexOf('，'))
          item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
          if (item.message.indexOf('】') == -1) {
            item.content = item.message.slice(item.message.indexOf('，') + 1)
          } else {
            item.content = item.message.slice(item.message.lastIndexOf('】') + 1)
          }
        })
        this.track = data
        this.isTrack = true
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.waybill-box {
  width: 100%;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
}
.box-height {
  height: calc(100vh - 80px) !important;
}
.waybill-content {
  margin: 0 auto;
  background: var(--prev-bg-white);
  min-height: 100vh;
}
.content-width {
  width: 1200px;
}
.sign-lable {
  font-size: 16px;
}
.info_sty {
  line-height: 30px;
  margin-bottom: 10px;
}
.label-sty {
  font-size: 16px;
  color: var(--prev-color-text-primary);
}
.value-sty {
  font-size: 16px;
  color: var(--prev-color-text-primary);
  font-weight: bold;
}
</style>
